import * as React from "react";
import { Button, Upload, Tooltip, Menu, Dropdown, Switch, Collapse, } from 'antd';
import * as Lodash from 'lodash'
import HeaderSearch from './HeaderSearch';
import classnames from 'classnames';
import { Utils } from '../../../util';
import './headerButton.less'

const ButtonGroup = Button.Group;
const Panel = Collapse.Panel;

interface IProps {
  content: {
    isPlus?:boolean,
    isUpsert?: boolean,
    isSearch?: boolean,
    isDelete?: boolean,
    isBind?: boolean,
    plusTxt?: string,
    bindTxt?: string,
  },
  columns?: any,
  filter?: any,
  changeKey?: any,
  activeKey?: string ,
  plus?(): void,
  sort?(sort: any): void,
  search?(filter: any): void,
  reset?(): void, 
  batchDelete?(): void,
  bind?(): void
  // export?(filter: any): void,
  // upload?(): void,
  searchConfig?: any,
}

interface IState {
  switch: any,
  dropdownVisible: boolean,
  selectMenu: string,
}


class HeaderButton extends React.Component<IProps, IState> {
  searchForm: any
  state: IState = {
    switch: 'asc',
    dropdownVisible: false,
    selectMenu: 'id',
  };

  plus = () => {
    this.props.plus();
  }

  sort = (key: any) => {
    this.setState({ dropdownVisible: false, selectMenu: key })
    this.props.sort(`${Utils.firstUpperCase(key)} ${this.state.switch}`)
  }

  getFormData = () => {
    const arr: any = [];
    this.searchForm.validateFields((err: any, values: any) => {
      const { searchConfig } = this.props;

      for (var key in values) {
        let filterObj: any
        let name = key;
        let value = values[key];
        filterObj = Lodash.find(searchConfig, { key: key });
        let symbol;
        switch (filterObj.type) {
          case 'input':
            symbol = 0;
            break;
          case 'select':
            symbol = 5;
            break;
          default:
            symbol = 0;
            break;
        }
        const filter = {
          fkTableName: filterObj.fkName ? filterObj.fkName : '',
          field: name.includes(':') ? name.match(/[:](\S*)/)[1] : name,
          value: value,
          symbol: symbol,
          otherFilter: '',
          linkedSymbol: 10
        }
        if (value) arr.push(filter)
      }
    });
    return arr
  }

  search = () => {
    const values = this.getFormData();
    this.props.search(values)
  }

  reset = () => {
    this.searchForm.resetFields();
    this.props.reset();
  }

  // export = () => {
  //   const values = this.getFormData();
  //   this.props.export(values);
  // }

  batchDeleteData = () => {
    this.props.batchDelete();
  }

  bind = () => {
    this.props.bind();
  }

  changeSwitch = (checked: boolean) => {
    const { selectMenu } = this.state;
    if (checked) {
      this.setState({ switch: 'asc' })
      this.props.sort(`${Utils.firstUpperCase(selectMenu)} asc`)
    } else {
      this.setState({ switch: 'desc' })
      this.props.sort(`${Utils.firstUpperCase(selectMenu)} desc`)
    }
  }

  menu = () => {
    const { columns } = this.props;
    const { selectMenu } = this.state;

    return columns.map((column: any, index: number) => {
      if (column.title !== '序号' && column.title !== '操作' && column.dataIndex ) {
        return (
          <Menu.Item
            className={
              column.key === selectMenu|| column.dataIndex === selectMenu
              ? classnames('select-menu') : ''}
            key={index}
            onClick={() =>
              this.sort(column.key || column.dataIndex)}
          >{column.title}</Menu.Item>
        )
      } else {
        return ''
      }
    })
  }

  dropdownVisibleChange = (visible: boolean) => {
    this.setState({ dropdownVisible: visible })
  }

  render() {
    const { columns } = this.props;
    const { isUpsert, isSearch, isDelete, isBind = true, isPlus = true, plusTxt, bindTxt = '批量绑定关系'} = this.props.content;

    const { searchConfig } = this.props;

    const menu = (
      <Menu>
        {isSearch ? this.menu() : ''}
        <Menu.Item>
          <Switch
            size="small"
            checkedChildren="正序"
            unCheckedChildren="倒序"
            defaultChecked
            onChange={(checked) => this.changeSwitch(checked)}
          />
        </Menu.Item>
      </Menu>
    );

    return (
      <div>
        <ButtonGroup>
          { isPlus
            ? <Tooltip placement="top" title={plusTxt || '添加'}>
              <Button icon="plus" onClick={() => { this.plus() }} >{plusTxt || '添加'}</Button>
            </Tooltip>
            : ''}
          {isSearch
            ? <Tooltip placement="top" title='排序'>
              <Dropdown
                overlay={menu}
                trigger={['hover', 'click']}
                visible={this.state.dropdownVisible}
                onVisibleChange={(visible) => { this.dropdownVisibleChange(visible) }}
              >
                <Button icon="menu-fold">排序</Button>
              </Dropdown>
            </Tooltip>
            : ''}
          {isSearch
            ? <Tooltip placement="top" title='搜索'>
                <Button
                  icon="search"
                  onClick={ this.search}
                >搜索</Button>
              </Tooltip>
            : ''}
          {isSearch
            ? <Tooltip placement="top" title='重置搜索'>
              <Button icon="stop" onClick={this.reset} 
              >重置</Button>
            </Tooltip>
            : ''}
          {isDelete
            ? <Tooltip placement="top" title='批量删除'>
              <Button
                icon="delete"
                onClick={this.batchDeleteData}
              >批量删除</Button>
            </Tooltip>
            : ''}
          {isBind
            ? <Tooltip placement="top" title='不能重复绑定关系哟'>
              <Button
                icon="tags"
                onClick={this.bind}
              >{bindTxt}</Button>
            </Tooltip>
            : ''
          }
          
          {/* {isSearch
            ? <Tooltip placement="top" title='导出'>
              <Button
                icon="export"
                onClick={() => { this.props.export(this.props.filter) }}
              >导出</Button>
              </Tooltip>
              : ''}
          {isUpsert
            ? <Upload {...this.props.upload}>
              <Tooltip placement="top" title='导入'>
                <Button icon="file-add"
                >导入</Button>
              </Tooltip>
            </Upload>
            : ''} */}
        </ButtonGroup>
        {
          isSearch
            ? <Collapse bordered={false} defaultActiveKey={['1']} >
              <Panel
                header='展开搜索项'
                key="1"
              >
                <HeaderSearch
                  searchConfig={searchConfig}
                  ref={ref => this.searchForm = ref}
                />

              </Panel>
            </Collapse>
            : ''
        }
      </div>
    )
  }
}

export default HeaderButton;
